public class Solution {

    public class TreeNode {
     int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
    public int priIndex;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length -1);
    }

    private TreeNode buildTreeChild(int[] preorder,int[] inorder,int inBegin,int inEnd){

        if(inBegin > inEnd){//没有左树或者右数  1
            return null;
        }
        TreeNode root = new TreeNode(preorder[priIndex]);//根据前序遍历 创建每个根节点  2


        int rootIndex = findIndex(inorder,inBegin,inEnd,preorder[priIndex]);//在中序遍历找到根节点的位置  3
        if(rootIndex == -1){
            return null;
        }


        priIndex++;
        //创建左子树和右子树    4
        root.left = buildTreeChild(preorder,inorder,inBegin,rootIndex -1);
        root.right = buildTreeChild(preorder,inorder,rootIndex +1,inEnd);

        return root;
    }

    private int findIndex(int[] inorder,int inBegin,int inEnd,int key){
        for(int i = 0;i <= inEnd; i++){
            if(inorder[i] == key){
                return i;
            }
        }
        return -1;
    }
}
